import { ref } from 'vue';
import {
  ItemType,
  FetchFuncType,
  AddFuncType,
  EditFuncType,
  DeleteFuncType,
  EStatusType
} from './useCommonVisitType';

import { useMessageNotify } from 'src/hook/common/useMessageNotify';
import { ECommonConst } from 'src/util/BaseConst';
import { PaginationItem } from 'src/util/Base';


export const useCommonVisitDatabase = (
  itemData: ItemType,
  fetchApi: FetchFuncType,
  confirmAddApi: AddFuncType,
  confirmEditApi: EditFuncType,
  deleteApi: DeleteFuncType
) => {
  //分页信息
  let dbPagination = ref<PaginationItem>({
    pageNum: 1,
    pageSize: ECommonConst.PAGE_SIZE,
    total: 0
  });

  //当前索引
  let dbCurrentIndex = ref<number|null>(null);

  //数据list
  let dbList = ref<ItemType[]>([]);

  //过滤数据list
  let dbFilterList = ref<ItemType[]>([]);

  //记录操作状态
  let dbStatus = ref<EStatusType>(EStatusType.FREE_TYPE);

  //消息通知hook
  const {
    showMessage,
    showSuccessMessage
  } = useMessageNotify();

  //过滤函数
  const filterList = (filter: string|null) => {
    dbFilterList.value.length = 0;
    if (filter !== null) {
      let str = filter.toLowerCase();
      dbList.value.forEach((item: ItemType) => {
        let sv = '';
        let bFilter = false;
        Object.keys(item).forEach((k) => {
          if (typeof (item[k]) === 'string') {
            sv = item[k].toLowerCase();
            if ((!bFilter) && (sv.indexOf(str) !== -1)) {
              bFilter = true;
              dbFilterList.value.push(item);
            }
          } else if (typeof (item[k]) === 'number') {
            sv = item[k].toString().toLowerCase();
            if ((!bFilter) && (sv.indexOf(str) !== -1)) {
              bFilter = true;
              dbFilterList.value.push(item);
            }
          }
        });
      });
    } else {
      dbList.value.forEach((item: ItemType) => {
        dbFilterList.value.push(item);
      });
    }
  }

  //修改数据
  const refreshItemData = (item: ItemType) => {
    if ((item.id >= 0) && (item.id < dbList.value.length)) {
      dbList.value[item.id] = item;
    }
  }

  //获取当前操作对象
  const getActiveItem = (): ItemType|null => {
    if ((dbCurrentIndex.value !== null) && (dbList.value) &&
      (dbCurrentIndex.value < dbList.value.length)) {
      return dbList.value[dbCurrentIndex.value];
    }

    return null;
  }

  //获取操作对象
  const getItem = (index: number): ItemType|null => {
    if ((dbList.value) && (index >= 0) && (index < dbList.value.length))  {
      return dbList.value[index];
    }
    return null;
  }

  //获取列表数据
  const loadList = () => {
    //初始状态
    dbStatus.value = EStatusType.FREE_TYPE;
    dbCurrentIndex.value = null;

    //开始加载
    fetchApi().then((res: any) => {
      if (res.data.message === 'Success') {
        //自定义返回格式Restful
        dbList.value.length = 0;
        dbList.value = res.data.data.list;
        dbPagination.value.total = res.data.data.total;

        //默认无过滤
        filterList(null);
      } else {
        showMessage(res.data.message);
      }
    }).catch((error: any) => {
      showMessage(error.message);
    });
  }

  //增加数据
  const addItem = () => {
    //添加在数组开头
    dbList.value.unshift(itemData);
    dbCurrentIndex.value = 0;
    dbStatus.value = EStatusType.ADD_TYPE;
  }

  //修改数据
  const editItem = (index: number) => {
    if ((index !== null) && (index !== undefined) && (index < dbList.value.length) &&
      (dbList.value) && (dbList.value.length)) {
      dbCurrentIndex.value = index;
      dbStatus.value = EStatusType.EDIT_TYPE;
    }
  }

  //删除数据
  const deleteItem = (index: number) => {
    if ((index !== null) && (index < dbList.value.length) &&
      (dbList.value) && (dbList.value.length)) {
      let item = dbList.value[index];       //读取要删除值

      //删除
      deleteApi(item).then((res: any) => {
        if (res.data.message === 'Success') {
          //splice两个参数，删除
          dbList.value.splice(index, 1);

          //默认无过滤
          filterList(null);
        }
      }).catch((error: any) => {
        showMessage(error.message);
      });
    }

    //清空
    dbCurrentIndex.value = null;
    dbStatus.value = EStatusType.FREE_TYPE;
  }

  //取消刚才添加的数据
  const cancelItem = (index: number) => {
    dbCurrentIndex.value = null;
    dbStatus.value = EStatusType.FREE_TYPE;
    if (index === 0) {
      //splice两个参数，删除
      dbList.value.splice(0, 1);

      //默认无过滤
      filterList(null);
    }
  };


  //在后台新增或更新数据
  const confirmApi = (item: ItemType) => {
    const api = (dbStatus.value === EStatusType.ADD_TYPE) ? confirmAddApi : confirmEditApi;
    api(item).then((res: any) => {
      if (res.data.message === 'Success') {
        loadList();
        showSuccessMessage('操作成功！')
      } else {
        showMessage(res.data.message);
      }
    }).catch((error: any) => {
      showMessage(error.message)
    });

    dbStatus.value = EStatusType.FREE_TYPE;
    dbCurrentIndex.value = null;
  };


  return {
    dbList,
    dbFilterList,
    dbPagination,
    dbCurrentIndex,
    dbStatus,
    refreshItemData,
    getActiveItem,
    getItem,
    filterList,
    loadList,
    addItem,
    editItem,
    deleteItem,
    cancelItem,
    confirmApi
  };
};

export default useCommonVisitDatabase;
